<script setup>
import { ref } from 'vue';
const props = defineProps({
  // 数据请求方法
  getData: {
    type: Function,
    required: true
  },
  // 返回结果
  modelValue: {
    type: Array,
    required: true
  },
  // 请求参数
  parmas: {
    type: Object,
    default () {
      return {}
    }
  }
})
const emit = defineEmits(['update:modelValue'])
const loading = ref(false);
const finished = ref(false);
const refreshing = ref(false)
let page = 1 // 页码
let pageSize = 10 // 每页数量
let len = 0 // 和总数比较确定是否已全部加载
// 刷新
const onRefresh = () => {
  page = 1
  len = 0
  finished.value = false
  refreshing.value = true
  emit('update:modelValue', [])
  onLoad()
};

// 获取数据
const onLoad = async () => {
  // 异步更新数据
  props.getData({ page, pageSize, ...props.parmas }).then((res) => {
    const {data, total} = res
    emit('update:modelValue', props.modelValue.concat(data))
    len += data.length
    if(len >= total) {
      finished.value = true
    }
    page++
  }).catch((err) => {
    console.log(err)
    finished.value = true
  }).finally(() => {
    // 加载状态结束
    refreshing.value = false
    loading.value = false
  })
};
</script>

<template>
  <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
    <van-list
      v-model:loading="loading"
      :finished="finished"
      :finished-text="props.modelValue.length ? '没有更多了' : ''"
      @load="onLoad"
    >
      <slot />
      <van-empty v-if="props.modelValue.length === 0 && !refreshing && !loading" description="暂无数据" />
    </van-list>

  </van-pull-refresh>
</template>
